// src/store/features/user/userSlice.ts
import type { LoginForm, userInfo } from "@/types/login";
import { createAsyncThunk, createSlice, type PayloadAction } from "@reduxjs/toolkit";
import { createTransform, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage"; // localStorage
import { encrypt, decrypt } from "@/utils/crypto";
import { logout } from "@/api/modules/login";
import { getRouter } from "@/router/index";

// 创建 transform
const AuthTransform = createTransform(
  // 在存入 storage 之前（inboundState）
  (inboundState: any) => {
    if (typeof inboundState !== "object" || inboundState === null) {
      return null;
    }
    return {
      ...inboundState,
      password: inboundState.password ? encrypt(inboundState.password) : null, // 简单 base64 加密
    };
  },
  // 在从 storage 恢复之后（outboundState）
  (outboundState: any) => {
    if (typeof outboundState !== "object" || outboundState === null) {
      return null;
    }
    return {
      ...outboundState,
      password: outboundState.password ? decrypt(outboundState.password) : null,
    };
  },
  // 只作用于 loginForm
  { whitelist: ["loginForm"] }
);

const persistConfig = {
  key: "user",
  storage,
  transforms: [AuthTransform], // 添加 transform 到配置中
};

interface UserState {
  userInfo: userInfo | null;
  rememberMe: boolean;
  loginForm: LoginForm | null;
}

const initialState: UserState = {
  userInfo: null,
  rememberMe: false,
  loginForm: null,
};

/** 退出登录 */
export const handleLogout = createAsyncThunk("user/logout", async () => {
  try {
    const res = await logout();
    window.localStorage.removeItem("token");
    window.localStorage.removeItem("refresh_token");

    const route = getRouter();
    route.navigate("/login");
    return res;
  } catch (error) {
    return error;
  }
});

export const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    setUserInfo(state, action: PayloadAction<any>) {
      state.userInfo = action.payload;
    },
    setRememberMe(state, action: PayloadAction<boolean>) {
      state.rememberMe = action.payload;
    },
    setLoginForm(state, action: PayloadAction<LoginForm>) {
      state.loginForm = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder
      /* ------  ❻ 请求刚刚发出去  ------ */
      // .addCase(handleLogout.pending, (state) => {})
      /** ------  ❻ 请求成功  ------ */
      .addCase(handleLogout.fulfilled, (state) => {
        state.userInfo = null;
      });
    /* ------  ❽ 接口抛异常  ------ */
    // .addCase(handleLogout.rejected, (state, action) => {});
  },
});

// 导出同步 action creators
export const { setUserInfo, setRememberMe, setLoginForm } = userSlice.actions;

export default persistReducer(persistConfig, userSlice.reducer);
